#include "home.h"
#include "ui_home.h"

Home::Home(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Home)
{
    ui->setupUi(this);

//    QFile qss_file(":/qss/style/home.qss"); // 使用资源系统来加载，如果是普通路径，请调整
//    if (qss_file.open(QFile::ReadOnly)) {
//        QString qss_text = QLatin1String(qss_file.readAll());
//        this->setStyleSheet(qss_text);
//        qss_file.close();
//    }
        // 连接 QComboBox 的信号和槽
        connect(ui->comboBox, SIGNAL(activated(QString)), this, SLOT(modeChange(QString)));

        // 连接按钮的点击信号
        connect(ui->pushButtonConnect, SIGNAL(clicked()), this, SLOT(onPushButtonClicked()));
        connect(ui->refresh, SIGNAL(clicked()), this, SLOT(sendRefresh()));
        // 初始设置
        ui->pushButtonConnect->setVisible(false);
        ui->spinBox->setVisible(false);
        ui->refresh->setVisible(false);

}

Home::~Home()
{
    delete ui;
}

void Home::paintEvent(QPaintEvent *)
{
    QPixmap bg(":/new/img/background.jpg");
    QPainter painter(this);
    painter.drawPixmap(0,0,width(),height(),bg);
}


void Home::modeChange(QString item) {
    // 根据选择的项设置按钮和 spinBox 的可见性
    if (item == "变化上报模式") {
        ui->pushButtonConnect->setVisible(false);
        ui->spinBox->setVisible(false);
        ui->refresh->setVisible(false);

        reportData("变化上报模式");
    } else if (item == "周期上报模式") {
        ui->pushButtonConnect->setVisible(true);
        ui->spinBox->setVisible(true);
        ui->refresh->setVisible(false);

    } else if (item == "刷新上报模式") {
        ui->pushButtonConnect->setVisible(false);
        ui->spinBox->setVisible(false);
        ui->refresh->setVisible(true);

        reportData("刷新上报模式");

    }
}

void Home::onPushButtonClicked() {
    // 获取按钮的文本并根据文本上报数据
    QString buttonText = ui->pushButtonConnect->text();
    if (buttonText == "确定") {
        reportData("周期上报模式");
    }
}

void Home::reportData(QString mode) {
    QJsonObject jsonObj;
    QJsonObject dataObj;
    jsonObj["type"] = 3;

    if (mode == "刷新上报模式") {
        dataObj["type"] = 0;
        dataObj["period"] = 0;
    } else if (mode == "变化上报模式") {
        dataObj["type"] = 1;
        dataObj["period"] = 0;
    }else if (mode == "周期上报模式") {
        dataObj["type"] = 2;
        int time = ui->spinBox->text().toInt();
        dataObj["period"] = time;
    }

    jsonObj["data"] = dataObj;
    QJsonDocument jsonDoc;
    jsonDoc.setObject(jsonObj);
    QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);
    emit sendmessage(jsonData);
}

void Home::sendRefresh() {
    QJsonObject jsonObj;
    QJsonObject dataObj;
    jsonObj["type"] = 1;
    jsonObj["limit"] = "all"; // 数据点范围
    jsonObj["keys"] = 0;

    QJsonDocument jsonDoc;
    jsonDoc.setObject(jsonObj);
    QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);

    // 发送消息
    emit sendmessage(jsonData);
    //qDebug() << "Sending JSON data:" << jsonData;
}




